<?php
class ModelExtensionOauthWechatUser extends Model
{
    protected $table = 'wechat_user';

    public function find($key)
    {
        $tbl = $this->getTable();
        $key_name = $this->getKeyName();

        $sql = "SELECT * FROM $tbl WHERE $key_name = '$key' ";

        $query = $this->db->query($sql);

        return $query->row;
    }

    /**
     * @param $customer_id
     * @param $key_user_id
     *
     * @return int
     */
	public function bindCustomer($customer_id, $key_user_id)
    {
        $user = $this->find($key_user_id);
        if (! $user) {
            return 0;
        }

        $tbl = $this->getTable();
        $union_id = $user['unionid'];
        $sql = "UPDATE $tbl SET customer_id = '$customer_id' WHERE unionid = '$union_id' "; // 同时更新 App 和 Pc

        $query = $this->db->query($sql);

        return $query->num_rows;
	}


    /**
     * @param array $user_info
     *
     * @return array
     * @throws Exception
     */
    public function updateOrCreateUserInfo($user_info)
    {
        $tbl = $this->getTable();

        $openid = $user_info['openid'];
        $user = $this->findByOpenId($openid);

        $user_info = $this->appendCustomerIdIfHasSameUnionUser($user_info);
        $set_data_sql = $this->assembleSetSql($user_info);

        $updated_at = '`updated_at` = NOW()';

        if ($user) {
            $sql = "UPDATE $tbl SET $set_data_sql, $updated_at WHERE `openid` = '$openid'";
            $query = $this->db->query($sql);
        } else {
            $sql = "INSERT INTO $tbl SET $set_data_sql, $updated_at";
            $query = $this->db->query($sql);

            $user = $this->findByOpenId($openid);
        }

        if (! $query->num_rows) {
            throw new \Exception('sql error');
        }

        return $user_info + $user;
    }

    /**
     * @param $openid
     *
     * @return mixed
     */
    public function findByOpenId($openid)
    {
        $tbl = $this->getTable();
        $sql = "SELECT * FROM $tbl WHERE openid = '$openid' ";

        $query = $this->db->query($sql);

        return $query->row;
    }

    public function findByUnionId($unionid)
    {
        $tbl = $this->getTable();
        $sql = "SELECT * FROM $tbl WHERE unionid = '$unionid' ";

        $query = $this->db->query($sql);

        return $query->row;
    }

    /**
     * App / Pc 可能有一个先绑定了，同一个开放平台 openid 不同，但 unionid 相同
     *
     * @param $user_info
     *
     * @return mixed
     */
    protected function appendCustomerIdIfHasSameUnionUser($user_info)
    {
        $unionid = $user_info['unionid'];
        $unionid_find = $this->findByUnionId($unionid);
        if ($unionid_find) {
            $user_info['customer_id'] = $unionid_find['customer_id'];
        }

        return $user_info;
    }
}
